package com.korion.kdyassistant.base

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.accessibilityservice.GestureDescription
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Path
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import com.korion.kdyassistant.R
import com.korion.kdyassistant.utils.showToast


class KdyAssistantService: AccessibilityService(){

    companion object {
        private const val TAG = "KdyAssistantService"
        private var assistantService: KdyAssistantService? = null

        fun performClick(x: Int, y: Int){
            assistantService?.performClickInternal(x, y)
        }
    }

    private var ready = false
    private var mAccessibilityServiceInfo: AccessibilityServiceInfo? = null
    private var back: String = ""
    private var home: String = ""
    private var recent: String = ""

    override fun onCreate() {
        super.onCreate()
        back = getVirtualNavigationKey(this, "accessibility_back", "com.android.systemui", "")
        home = getVirtualNavigationKey(this, "accessibility_home", "com.android.systemui", "")
        recent = getVirtualNavigationKey(this, "accessibility_recent", "com.android.systemui", "")

        mAccessibilityServiceInfo = AccessibilityServiceInfo()
        mAccessibilityServiceInfo?.apply {
            this.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            this.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED or
                    AccessibilityEvent.TYPE_VIEW_LONG_CLICKED or
                    AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
            var flags = 0
            flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
            flags = flags or AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS
            this.flags = flags
            this.notificationTimeout=100;
        }
        serviceInfo = mAccessibilityServiceInfo
    }

    override fun onInterrupt() {
        //ignore
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        //虚拟手机按键处理
        if (!TextUtils.isEmpty(event.contentDescription) && ("com.android.systemui" == event.packageName))
        {
            Log.d(TAG, "onAccessibilityEvent: key=${event.contentDescription}")
            //长按虚拟机触发的，需要转到按键处理去
            if (!TextUtils.isEmpty(back) && event.contentDescription == back){
//                KeyPressedTipViewController.getInstance().onKeyLongPress(KeyEvent.KEYCODE_BACK)
            }else if (!TextUtils.isEmpty(home) && event.contentDescription == home){
//                KeyPressedTipViewController.getInstance().onKeyLongPress(KeyEvent.KEYCODE_HOME)
            }else if (!TextUtils.isEmpty(recent) && event.contentDescription == recent){
//                KeyPressedTipViewController.getInstance().onKeyLongPress(KeyEvent.KEYCODE_APP_SWITCH)
            }
        }
    }

    override fun onServiceConnected() {
        Log.d(TAG, "KdyAssistantService#onServiceConnected")
        ready = true
        assistantService = this
        serviceInfo = mAccessibilityServiceInfo
    }

    override fun onKeyEvent(event: KeyEvent): Boolean {
        Log.d(TAG, "onKeyEvent:key code=${event.keyCode}, action=${event.action}")
        return super.onKeyEvent(event)
    }

    override fun onDestroy() {
        super.onDestroy()
        assistantService = null
    }

    private fun performClickInternal(x: Int, y: Int): Boolean{
        if (!ready){
            showToast(R.string.accessibility_service_close)
            return false
        }
        Log.d(TAG, "performClickInternal: $x, $y")
        val path = Path()
        path.moveTo(x.toFloat(), y.toFloat())
        val builder = GestureDescription.Builder()
        val gestureDescription = builder
            .addStroke(GestureDescription.StrokeDescription(path, 0L, 100L))
            .build()
        return dispatchGesture(gestureDescription, null, null)
    }

    private fun getVirtualNavigationKey(
        paramContext: Context,
        paramString1: String?,
        paramString2: String?,
        paramString3: String
    ): String {
        try {
            val packageManager = paramContext.packageManager.getResourcesForApplication(paramString2!!)
            return packageManager.getString(
                packageManager.getIdentifier(
                    paramString1,
                    "string",
                    paramString2
                )
            )
        } catch (e: PackageManager.NameNotFoundException) {
        }
        return paramString3
    }
}